import apiClient from '@/api/axios.js';

export class MarketItemApi {
    // 收藏商品
    static async favoriteItem(userID: number, itemID: number) {
        try {
            const response = await apiClient.post(
                '/market-item/item',
                {},
                {
                    params: { userID, itemID },
                    headers: {
                        'Content-Type': 'application/json',
                        Authorization: `Bearer ${localStorage.getItem('token')}`,
                    },
                }
            );
            return response.data;
        } catch (error) {
            throw new Error(error.message || '收藏商品失败');
        }
    }

    // 发送消息
    static async sendMessage(chatRoomID: number, senderID: number, content: string) {
        try {
            const response = await apiClient.post(
                '/market-item/send',
                {},
                {
                    params: { chatRoomID, senderID, content },
                    headers: {
                        'Content-Type': 'application/json',
                        Authorization: `Bearer ${localStorage.getItem('token')}`,
                    },
                }
            );
            return response.data;
        } catch (error) {
            throw new Error(error.message || '发送消息失败');
        }
    }

    // 根据商品ID创建会话
    static async createChatSession(user1ID: number, user2ID: number, itemID: number) {
        try {
            const response = await apiClient.post(
                '/market-item/create',
                {},
                {
                    params: { user1ID, user2ID, itemID },
                    headers: {
                        'Content-Type': 'application/json',
                        Authorization: `Bearer ${localStorage.getItem('token')}`,
                    },
                }
            );
            return response.data;
        } catch (error) {
            throw new Error(error.message || '创建会话失败');
        }
    }

    // 通过关键词检索商品
    static async searchItems(keyword: string, pageNum: number = 1, pageSize: number = 40) {
        try {
            const response = await apiClient.get('/market-item/search', {
                params: { keyword, pageNum, pageSize },
                headers: {
                    'Content-Type': 'application/json',
                    Authorization: `Bearer ${localStorage.getItem('token')}`,
                },
            });
            return response.data;
        } catch (error) {
            throw new Error(error.message || '搜索商品失败');
        }
    }

    // 获取商品的所有图片
    static async getItemImages(itemID: number) {
        try {
            const response = await apiClient.get('/market-item/image', {
                params: { itemID },
                headers: {
                    'Content-Type': 'application/json',
                    Authorization: `Bearer ${localStorage.getItem('token')}`,
                },
            });
            return response.data;
        } catch (error) {
            throw new Error(error.message || '获取商品图片失败');
        }
    }

    // 根据商品ID获取商品的第一张图片
    static async getFirstItemImage(itemID: number) {
        try {
            const response = await apiClient.get('/market-item/firstimage', {
                params: { itemID },
                headers: {
                    'Content-Type': 'application/json',
                    Authorization: `Bearer ${localStorage.getItem('token')}`,
                },
            });
            return response.data;
        } catch (error) {
            throw new Error(error.message || '获取第一张图片失败');
        }
    }

    // 根据时间分页查询商品
    static async getItemsByTime(startTime: string, endTime: string, pageNum: number, pageSize: number) {
        try {
            const response = await apiClient.get('/market-item/pageByTime', {
                params: { start_time: startTime, end_time: endTime, pageNum, pageSize },
                headers: {
                    'Content-Type': 'application/json',
                    Authorization: `Bearer ${localStorage.getItem('token')}`,
                },
            });
            return response.data;
        } catch (error) {
            throw new Error(error.message || '按时间查询商品失败');
        }
    }

    // 举报商品
    static async reportItem(itemID: number, reason: string) {
        try {
            const response = await apiClient.post(
                '/market-item/report',
                {},
                {
                    params: { itemID, reason },
                    headers: {
                        'Content-Type': 'application/json',
                    },
                }
            );
            return response.data;
        } catch (error) {
            throw new Error(error.message || '举报商品失败');
        }
    }

    // 评价交易
    static async evaluateTransaction(params: {
        orderID: number;
        itemID: number;
        buyerID: number;
        sellerID: number;
        status: 'inProgress' | 'completed' | 'cancelled';
        buyerRating: number;
        buyerReview: string;
        createTime: string;
        addrID: number;
    }) {
        try {
            const response = await apiClient.post('/market-item/evaluate', params, {
                headers: {
                    'Content-Type': 'application/json',
                    Authorization: `Bearer ${localStorage.getItem('token')}`,
                },
            });
            return response.data;
        } catch (error) {
            throw new Error(error.message || '评价交易失败');
        }
    }

    // 购买商品
    static async purchaseItem(params: {
        itemID: number;
        buyerID: number;
        sellerID: number;
        status: 'inProgress' | 'completed' | 'cancelled';
        createTime: string;
        addrID: number;
    }) {
        try {
            const response = await apiClient.post('/market-item/purchase', params, {
                headers: {
                    'Content-Type': 'application/json',
                    Authorization: `Bearer ${localStorage.getItem('token')}`,
                },
            });
            return response.data;
        } catch (error) {
            throw new Error(error.message || '购买商品失败');
        }
    }

    // 发布商品
    static async publishItem(params) {
        const {
            sellerID,
            title,
            description,
            price,
            status = 'forSale', // 默认值
            creationTime = new Date().valueOf(),
            images = []         // 图片URL数组
        } = params;

        // 构建符合API格式的参数
        const requestBody = {
            secondhanditem: {
                sellerID: parseInt(sellerID),
                title,
                description,
                price,
                status,
                creationTime
            },
            image: images
        };

        try {
            console.log("发布商品参数:", requestBody);

            const response = await apiClient.post(
                '/market-item/publish',
                requestBody,
                {
                    headers: {
                        'Content-Type': 'application/json',
                    },
                }
            );
            return response.data;
        } catch (error) {
            throw new Error(error.message || '发布商品失败');
        }
    }
}
